package com.example.chat03.config;

import com.example.chat03.model.StompAuthenticatedUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

/**
 * 自定义用户认证拦截器
 */
public class UserAuthenticationChannelInterceptor implements ChannelInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserAuthenticationChannelInterceptor.class);

    public static final String USER_NAME = "User-Name";

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        // 如果是连接请求，记录 username
        if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())){
            String username = accessor.getFirstNativeHeader(USER_NAME);
            logger.info("找到 Stomp 用户相关标头,username: {}",username);
            accessor.setUser(new StompAuthenticatedUser(username));
        }
        return ChannelInterceptor.super.preSend(message,channel);
    }
}
